import java.util.PriorityQueue;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-08
 * Time: 15:04
 */

//描述一个任务
class MyTimerTask implements Comparable<MyTimerTask> {
    private Runnable runnable;//要执行的任务
    private long time;//任务时间

    public MyTimerTask(Runnable runnable, long delay) {
        //delay:
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public void run() {
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int) (this.time - o.time);//
    }

    public long getTime() {
        return time;
    }
}

class MyTimer {
    //使用堆存储任务
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();

    private Object locker = new Object();

    public MyTimer() {
        Thread t = new Thread(() -> {
            try {
                while (true) {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            //为空
                            locker.wait();
                        }
                        MyTimerTask timerTask = queue.peek();
                        if (System.currentTimeMillis() >= timerTask.getTime()) {
                            //要执行
                            timerTask.run();
                            queue.poll();//执行完必后,把这个任务删除
                        } else {
                            //先不执行
                            locker.wait(timerTask.getTime() - System.currentTimeMillis());
                        }
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
        t.start();
    }

    //安排任务
    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            MyTimerTask task = new MyTimerTask(runnable, delay);
            queue.offer(task);
            locker.notify();
        }
    }
}

public class demo2 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer timer = new MyTimer();
        timer.schedule(() -> {
            System.out.println("Hello1");
        }, 1000);
        Thread.sleep(4000);
    }
}
